import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/train/model/train_stream.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';

import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/14.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainTeacherCourseItemWidget extends StatefulWidget {
  final CourseAndTeacherBean cubean;
  final int index;

  final isScaffold;

  const TrainTeacherCourseItemWidget(
      {Key key, this.cubean, this.index, this.isScaffold = true})
      : super(key: key);

  @override
  _TrainTeacherCourseItemWidgetState createState() =>
      _TrainTeacherCourseItemWidgetState();
}

class _TrainTeacherCourseItemWidgetState
    extends State<TrainTeacherCourseItemWidget>
    with SingleTickerProviderStateMixin, TrainModel {
  bool _isOpen = false;
  AnimationController _animationController;
  Animation<Offset> _animation;

  //消息订阅监听对象
  StreamSubscription _levelCourseStreamSubscription;

  @override
  void initState() {
    super.initState();
    _animationController = new AnimationController(
        vsync: this,
        duration: Duration(microseconds: 400),
        lowerBound: 0.0,
        upperBound: 0.25);
    _animation = new Tween(begin: Offset(0, -0.5), end: Offset(0.0, 0.0))
        .animate(_animationController);

    // _list = widget.cubean.courseEntity.courseList;
    if (_list != null && _list.length > 0) {
      _isLoading = false;
    }

    //添加消息监听
    _levelCourseStreamSubscription =
        trainStream.stream.listen((TrainEventBean event) {
      if (event.statues == 0) {
        CourseBean level = event.data;
        //刷新
        for (int i = 0; i < _list.length; i++) {
          CourseBean itemCourseBean = _list[i];
          if (itemCourseBean.courseId == level.courseList[0].courseId) {
            itemCourseBean.studyStatues = level.studyStatues;
            setState(() {});
            break;
          }
        }
      }
    });
  }

  List<CourseBean> _list = [];

  @override
  void dispose() {
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _animationController.dispose();
    //移除消息监听
    _levelCourseStreamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 6),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              ClipOval(
                child: Container(
                  alignment: Alignment.center,
                  width: 14,
                  height: 14,
                  child: Text(
                    "${widget.index + 1}",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                  decoration: BoxDecoration(
                      gradient: LinearGradient(colors: [
                    Colors.blueAccent,
                    Colors.lightBlueAccent,
                    Colors.blue,
                  ])),
                ),
              ),
              SizedBox(
                width: 8,
              ),
              Text("${widget.cubean.userEntity.username}"),
              SizedBox(
                width: 8,
              ),
              Expanded(
                child: Text("《${widget.cubean.teacherContent}》"),
              ),
              RotationTransition(
                turns: _animationController,
                child: InkWell(
                    onTap: () {
                      if (!_isOpen) {
                        _isOpen = true;
                        if (_list.length == 0) {
                          getCourseLevelList();
                        }
                        _animationController.reset();
                        _animationController.forward();
                      } else {
                        _isOpen = false;
                        _animationController.reverse();
                      }
                      setState(() {});
                    },
                    child: Icon(Icons.arrow_right)),
              )
            ],
          ),
          buildFlagContainer(),
          Container(
            child: buildCourseLevel(),
            padding: EdgeInsets.only(left: 22),
          ),
        ],
      ),
    );
  }

  ///完成比例
  Container buildFlagContainer() {
    double flag = 0.0;
    if (widget.cubean.finishLevelNumber != null &&
        widget.cubean.totalLevelNumber != null &&
        widget.cubean.totalLevelNumber > 0) {
      flag = widget.cubean.finishLevelNumber / widget.cubean.totalLevelNumber;
    }
    LogUtils.e(
        "flag $flag finishLevelNumber ${widget.cubean.finishLevelNumber} totalLevelNumber ${widget.cubean.totalLevelNumber}");
    return Container(
      padding: EdgeInsets.only(left: 22, top: 2),
      child: Row(
        children: [
          Text(
            "完成比例",
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
          Container(
            width: 100,
            height: 16,
            margin: EdgeInsets.only(left: 8, right: 8),
            child: Stack(
              children: [
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.all(Radius.circular(4))),
                  ),
                ),
                ClipRRect(
                  child: Align(
                    widthFactor: flag,
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.green,
                          borderRadius: BorderRadius.all(Radius.circular(4))),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Text(
            "${(flag * 100).toInt()}%",
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ],
      ),
    );
  }

  buildCourseLevel() {
    if (!_isOpen) {
      return Container();
    }
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_list.length == 0) {
      return Text("暂无课程小节");
    }
    return Stack(
      children: [
        ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: _list.length,
          itemBuilder: (BuildContext context, int index) {
            CourseBean courseBean = _list[index];

            return Container(
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      "${widget.index + 1}-${index + 1}  ${courseBean.courseName}",
                      style: TextStyle(fontSize: 12),
                    ),
                  ),
                  buildRightButton(context, courseBean)
                ],
              ),
            );
          },
        ),
        _commitLoading
            ? Positioned.fill(
            child: Container(
              color: Colors.white.withOpacity(0.8),
              child: CupertinoActivityIndicator(),
            ))
            : Container(),
      ],
    );
  }

  Widget buildRightButton(BuildContext context, CourseBean courseBean) {
    int studyStatues = courseBean.studyStatues;
    if (studyStatues != null) {
      if (studyStatues == 0) {
        return Container(
          alignment: Alignment.center,
          padding: EdgeInsets.only(right: 6),
          child: Text(
            "正在开课中...",
            style: TextStyle(color: Colors.green),
          ),
        );
      } else {
        return Container(
          alignment: Alignment.center,
          padding: EdgeInsets.only(right: 6),
          height: 36,
          child: Text(
            "已开课完毕",
            style: TextStyle(color: Colors.grey),
          ),
        );
      }
    }

    UserBean userBean = UserHelper.getInstance.userBean;
    if (userBean.userType == 12) {
      return ElevatedButton(
        child: Text("开始上课"),
        onPressed: () {
          startCourseFunction(courseBean);
        },
      );
    }

    return Text(
      "请等待开课...",
      style: TextStyle(color: Colors.grey),
    );
  }

  bool _commitLoading = false;

  //获取课程小节

  CancelToken _cancelToken;
  bool _isLoading = true;

  Future<bool> getCourseLevelList() async {
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url:
      HttpHelper.courseLevelUrl + "/${widget.cubean.id}",
      cancelTag: _cancelToken,
    );
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data;
      if (list != null) {
        _list = [];
        list.forEach((element) {
          _list.add(CourseBean.fromJson(element));
        });
      }
    }
    _isLoading = false;
    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }

  void startCourseFunction(CourseBean courseBean) async {
    _commitLoading = true;
    setState(() {});
    bool flag = await teacherStartCourseNetDatils(
      courseOneId: widget.cubean.id,
      courseTwoId: courseBean.courseId,
      trainId: widget.cubean.trainId,
    );

    if (flag) {
      if (widget.isScaffold) {
        Navigator.of(context).pop(courseBean);
      } else {
        courseBean.studyStatues = 0;
        _commitLoading = false;
        //发送消息通知
        trainStream.add(TrainEventBean(2, courseBean));
        setState(() {});
      }
    } else {
      _commitLoading = false;
      setState(() {});
    }
  }
}
